jQuery(function(){
	var peditorpath = '';
	jQuery('script').each(function(){
		var jsrc = jQuery(this).attr('src');
		if (jsrc && jsrc.substring(jsrc.lastIndexOf("/")+1)=='peditor.js') {
			peditorpath = jsrc.substring(0, jsrc.lastIndexOf('/')+1);
			return false;
		}
	});
	var node = document.createElement('link');
	node.setAttribute('rel', 'stylesheet');
	node.setAttribute('href', peditorpath+'peditor.css');
	document.getElementsByTagName('head')[0].appendChild(node);

	var _cfg = {
			postUrl: window.location.href,
			hideAvatar: 0,
			pid: 0,
			tags: []
	};
	if (jQuery('#j-peditor').attr('data-post')) {
		_cfg.postUrl = jQuery('#j-peditor').attr('data-post');
	}
	if (jQuery('#j-peditor').attr('data-avatar')) {
		_cfg.hideAvatar = jQuery('#j-peditor').attr('data-avatar');
	}
	if (jQuery('#j-peditor').attr('data-pid')) {
		_cfg.pid = jQuery('#j-peditor').attr('data-pid');
	}
	if (jQuery('#j-peditor').attr('data-tags')) {
		_cfg.tags = jQuery('#j-peditor').attr('data-tags').split('|');
	}
	var _defaultTxt = '';
	for (var i in _cfg.tags) {
		_defaultTxt += '#' + _cfg.tags[i] + '# ';
	}

	var s = '<input type="hidden" name="iid"><input type="hidden" name="vid">';
	if (jQuery('#j-peditor').attr('data-admin') > 0) {
		s += '<p>用户：<input type="text" name="username" class="tit"></p>';
		s += '<p>回复：<input type="text" name="pid" class="tit"></p>';
	}
	s += '<textarea name="content" style="width:100%; height: 100px; border: 1px solid #ccc; resize: none;">'+_defaultTxt+'</textarea>';
	var sico = '';
	sico += '<a href="javascript:;" class="fce"><i></i>表情</a>';
	sico += '<span class="u-upload"><a href="javascript:;" class="img"><i></i>图片</a><input class="u-file" id="j-imguploader" type="file" name="fpimg" data-url="/misc/uploadpe"></span>';
	// sico += '<a href="javascript:;" class="vid"><i></i>视频</a>';
	sico += '<a href="javascript:;" class="blg"><i></i>长文</a>';
	var syncico = '';
	// syncico += '<a href="javascript:;" class="qq"><i></i></a>';
	syncico += '<a href="javascript:;" class="sina"><i></i><input type="checkbox" name="sync[]" value="sina" checked="checked" style="display: none;"></a>';
	s += '<table class="btn" width="100%"><tr><td><div class="u-pe-ico">'+sico+'</div></td><td width="60" align="right">分享到&nbsp;</td><td width="30"><div class="u-pe-syncico">'+syncico+'</div></td><td width="110" align="right"><input type="button" value="发布" class="u-btn u-btn-md u-btn-c3 j-submit"></td></tr></table>';
	jQuery('#j-peditor').html(s);
	if (jQuery('#j-peditor').attr('data-uid') > 0) {
		jQuery('#j-peditor .u-pe-syncico a').click(function(){
			jQuery(this).find('i').toggleClass('disable');
			var _icb = jQuery(this).find('input[type="checkbox"]');
			if (jQuery(this).find('i').hasClass('disable')) {
				_icb.removeAttr('checked');
			} else {
				_icb.attr('checked', 'checked');
			}
		});
		jQuery('#j-peditor .j-submit').click(function(){
			var _submitBtn = this;
			var content = jQuery('#j-peditor textarea').val();
			var iid = jQuery('#j-peditor input[name="iid"]').val();
			var vid = jQuery('#j-peditor input[name="vid"]').val();
			var sync = [];
			if (jQuery('#j-peditor input[name="pid"]').val() > 0) {
				_cfg.pid = jQuery('#j-peditor input[name="pid"]').val();
			}
			jQuery('#j-peditor input[name="sync[]"][checked="checked"]').each(function(){
				sync.push(jQuery(this).val());
			});
			if (!content && !iid) {
				jQuery('#j-peditor textarea').css('background', '#fee');
				setTimeout(function(){
					jQuery('#j-peditor textarea').css('background', '#fdd');
					setTimeout(function(){
						jQuery('#j-peditor textarea').css('background', '#fee');
						setTimeout(function(){
							jQuery('#j-peditor textarea').css('background', '#fdd');
							setTimeout(function(){
								jQuery('#j-peditor textarea').css('background', '#fee');
								setTimeout(function(){jQuery('#j-peditor textarea').css('background', '#fff');}, 120);
							}, 120);
						}, 120);
					}, 120);
				}, 120);
				return false;
			}
			jQuery.post(_cfg.postUrl, {content:content, iid:iid, vid:vid, pid:_cfg.pid, sync:sync, username:jQuery('#j-peditor input[name="username"]').val()}, function(r){
				if ( ! r.error) {
					var feeddl = '';
					if (r.data.metahtml) feeddl += '<p class="meta">'+r.data.metahtml+'</p>';
					if (r.data.iid) feeddl += '<p class="img"><a href="/'+r.data.id+'"><img src="'+r.data.iurl+'" alt=""></a></p>';
					feeddl += '<p class="info"><a href="/'+r.data.id+'">刚刚</a></p>';
					if ( ! _cfg.hideAvatar) {
						feeddl = '<div class="g-sd-l"><a href="/u/'+r.data.uid+'"><img src="'+r.data.avatar+'" alt="" class="avatar_s"></a></div><div class="g-mn-r"><div class="g-mn-r-c"><p class="user"><a href="/u/'+r.data.uid+'">'+r.data.username+'</a></p>'+feeddl+'</div></div><div class="cls"></div>';
					}
					feeddl = '<div class="m-item">'+feeddl+'</div>';
					jQuery('.j-feedlist').prepend(feeddl);
					jQuery('#j-peditor input[name=iid]').val('');
					jQuery('#j-peditor input[name=vid]').val('');
					jQuery('#j-peditor textarea').val(_defaultTxt);
					if (layer.index) layer.closeAll();
				} else {
					layer.tips(r.message, _submitBtn, {tips:1});
				}
			}, 'json');
		});
		jQuery('#j-peditor .u-pe-ico .fce').click(function(){
			var fcedata = {"smilea":"\u5475\u5475","tootha":"\u563b\u563b","laugh":"\u54c8\u54c8","tza":"\u53ef\u7231","kl":"\u53ef\u601c","kbsa":"\u6316\u9f3b\u5c4e","cj":"\u5403\u60ca","shamea":"\u5bb3\u7f9e","zy":"\u6324\u773c","bz":"\u95ed\u5634","bs2":"\u9119\u89c6","lovea":"\u7231\u4f60","sada":"\u6cea","heia":"\u5077\u7b11","qq":"\u4eb2\u4eb2","sb":"\u751f\u75c5","mb":"\u592a\u5f00\u5fc3","ldln":"\u61d2\u5f97\u7406\u4f60","yhh":"\u53f3\u54fc\u54fc","zhh":"\u5de6\u54fc\u54fc","x":"\u5618","cry":"\u8870","wq":"\u59d4\u5c48","t":"\u5410","k":"\u6253\u54c8\u6b20","bba":"\u62b1\u62b1","angrya":"\u6012","yw":"\u7591\u95ee","cza":"\u998b\u5634","bye":"\u62dc\u62dc","sk":"\u601d\u8003","sweata":"\u6c57","sleepya":"\u56f0","sleepa":"\u7761\u89c9","money":"\u94b1","sw":"\u5931\u671b","cool":"\u9177","hsa":"\u82b1\u5fc3","hatea":"\u54fc","gza":"\u9f13\u638c","dizzya":"\u6655","bs":"\u60b2\u4f24","crazya":"\u6293\u72c2","h":"\u9ed1\u7ebf","yx":"\u9634\u9669","nm":"\u6012\u9a82","hearta":"\u5fc3","unheart":"\u4f24\u5fc3","pig":"\u732a\u5934","ok":"ok","ye":"\u8036","good":"good","no":"\u4e0d\u8981","z2":"\u8d5e","come":"\u6765","sad":"\u5f31","lazu":"\u8721\u70db","clock":"\u949f","m":"\u8bdd\u7b52","cake":"\u86cb\u7cd5","shenshou":"\u8349\u6ce5\u9a6c","horse2":"\u795e\u9a6c","fuyun":"\u6d6e\u4e91","geili":"\u7ed9\u529b","wg":"\u56f4\u89c2","vw":"\u5a01\u6b66","panda":"\u718a\u732b","rabbit":"\u5154\u5b50","otm":"\u5965\u7279\u66fc","j":"\u56e7","hufen":"\u4e92\u7c89","liwu":"\u793c\u7269"};
			var fcehtml = '';
			for (var k in fcedata) {
				fcehtml += '<li><a href="javascript:;" title="'+fcedata[k]+'"><img src="'+peditorpath+'fce/'+k+'.gif"></a></li>';
			}
			var layidx = layer.open({
				type: 4,
				zIndex: 5,
				area: '404px',
				content: ['<div class="u-pe-fcebox"><ul>'+fcehtml+'</ul></div>', this],
				tips: [3, '#f9f3f3'],
				success: function(layerjq){
					layerjq.find('.u-pe-fcebox a').click(function(){
						var txt = jQuery(this).attr('title');
						fastInsertStr(jQuery('#j-peditor textarea'), '['+txt+'] ');
						layer.close(layidx);
					});
				},
				end: function(){
					var iid = jQuery('#j-peditor input[name=iid]').val();
					if (iid) {
						var ithumburl = jQuery('#j-peditor input[name=iid]').attr('data-thumb');
						var layidx_imgtip = layer.open({
							type: 4,
							zIndex: 3,
							area: '180px',
							content: ['<div class="u-pe-imgbox"><img src="'+ithumburl+'"><a class="del" href="javascript:;">删除</a></div>', jQuery('#j-peditor .u-pe-ico .img')[0]],
							tips: [3, '#f9f3f3'],
							success: function(layerjq){
								layerjq.find('.u-pe-imgbox .del').click(function(){
									jQuery('#j-peditor input[name=iid]').val('');
									layer.close(layidx_imgtip);
								});
							}
						});
					}
				}
			});
		});
		jQuery('#j-peditor #j-imguploader').fileupload({
			dataType: 'json',
			done: function(e, data) {
				jQuery('#j-peditor input[name=iid]').val(data.result.fullname);
				jQuery('#j-peditor input[name=iid]').attr('data-thumb', data.result.thumb);
				var layidx = layer.open({
					type: 4,
					zIndex: 3,
					area: '180px',
					content: ['<div class="u-pe-imgbox"><img src="'+data.result.thumb+'"><a class="del" href="javascript:;">删除</a></div>', jQuery('#j-peditor .u-pe-ico .img')[0]],
					tips: [3, '#f9f3f3'],
					success: function(layerjq){
						layerjq.find('.u-pe-imgbox .del').click(function(){
							jQuery('#j-peditor input[name=iid]').val('');
							layer.close(layidx);
						});
					}
				});
				return false;
			}
		});
		jQuery('#j-peditor .u-pe-ico .vid').click(function(){
			layer.alert('即将推出');
		});
		jQuery('#j-peditor .u-pe-ico .blg').click(function(){
			var formhtml = '<p>标题：<input type="text" name="title" class="tit"><input type="hidden" name="type" value="blog"></p>';
			formhtml += '<p>标签：<input type="text" name="tags" class="tit" value="'+_cfg.tags.join('|')+'"></p>';
			if (jQuery('#j-peditor').attr('data-admin') > 0) {
				formhtml += '<p>用户：<input type="text" name="username" class="tit"></p>';
				formhtml += '<p>回复：<input type="text" name="pid" class="tit" value="'+_cfg.pid+'"></p>';
			} else {
				formhtml += '<input type="hidden" name="pid" value="'+_cfg.pid+'">';
			}
			formhtml += '<p><textarea id="j-textareake" name="content" style="width:720px;height:400px;"></textarea></p>';
			formhtml += '<p style="text-align: right;"><input type="button" value="取消" class="u-btn u-btn-md u-btn-c4 close"> &nbsp; <input type="submit" value="发布" class="u-btn u-btn-md u-btn-c3"></p>';
			formhtml = '<form action="'+_cfg.postUrl+'" method="post">'+formhtml+'</form>'
			var layidx = layer.open({
				type: 1,
				area: '775px',
				title: false,
				shade: [1,'#fff'],
				offset: '20px',
				closeBtn: 0,
				zIndex: 9,
				content: '<div class="u-pe-blgbox"><div class="th"><a href="javascript:;" class="close">返回</a></div><div class="td">'+formhtml+'</div></div>',
				success: function(layerjq){
					var editor = KindEditor.create('#j-textareake', {uploadJson:'/misc/uploadke'});
					layerjq.find('.u-pe-blgbox .close').on('click', function(){
						layer.close(layidx);
					});
				}
			});
		});
	} else {
		jQuery('#j-peditor input').attr('disabled', 'disabled');
		jQuery('#j-peditor').css('position', 'relative').append('<div class="login-reqired"><table><tr><td><span>参与讨论之前请先 <a target="_blank" href="/auth/login">登录</a> 或 <a target="_blank" href="/auth/register">注册</a></span></td></tr></table></div>');
	}
});

function getRange(jotextarea) {
	var range;
	jotextarea.each(function() {
		if (document.selection) {
			range = document.selection.createRange();
		}
	});
	return range;
}

function insertStr(editor, value, range) {
	if (!editor || !value) return;
	editor.focus();
	if (range && range.parentElement() == editor) {
		range.text = value;
		range.select();
		range = null;
	} else if (document.selection) {
		document.selection.createRange().text = value;
	} else if (typeof editor.selectionStart != "undefined") { // firefox
		var str = editor.value;
		var start = editor.selectionStart;
		var scroll = editor.scrollTop;
		editor.value = str.substr(0, start) + value + str.substring(editor.selectionEnd, str.length);
		editor.selectionStart = start + value.length;
		editor.selectionEnd = start + value.length;
		editor.scrollTop = scroll;
	}
}

function fastInsertStr(jotextarea, str) {
	var s = jotextarea.attr('value');
	s = s.replace('#请在这里输入自定义话题#', '');
	jotextarea.val(s);
	range = getRange(jotextarea);
	var editor = jotextarea.get(0);
	insertStr(editor, str, range);
}